
#include "RFEventManager.h"

namespace Rooftop {

EventManager* EventManager::p_instance = NULL;

int EventManager::addEventListener(const char* estr)
{
    boost::signals2::signal<bool (EventBase &)> *sig = new boost::signals2::signal<bool (EventBase &)>();
    m_eventSignalMap.insert(estr, sig);        
    m_estrMap.push_back(estr);
}

int EventManager::addEventCallback(const char* estr, bool _cb(EventBase &))
{
    boost::shared_ptr<boost::signals2::signal<bool (EventBase &)> > sig(m_eventSignalMap.find(estr));
    sig->connect(_cb);
    sig.reset();
}

int EventManager::getNumSlots(std::string eventType)
{
    int count = 0;
    boost::shared_ptr<boost::signals2::signal<bool (EventBase &)> > sig( m_eventSignalMap.find(eventType.c_str()) );
    count = sig->num_slots();
    sig.reset();
    return count;
}

int EventManager::dispachEvent(EventBase &event)
{
    boost::shared_ptr<boost::signals2::signal<bool (EventBase &)> > sig( m_eventSignalMap.find(event.type().str()) );
    if (!sig.get()) {
        Log(LERROR, "can't get signal!");
        return -1;
    }

    if (!sig->num_slots())
        return -1;

    (*sig)(event);
    sig.reset();
    
    return 0;
}

boost::signals2::connection EventManager::addEventCallback(const char* estr, boost::signals2::signal<bool (EventBase &)>::slot_function_type cb)
{
    boost::shared_ptr<boost::signals2::signal<bool (EventBase &)> > sig(m_eventSignalMap.find(estr));
    boost::signals2::connection connect = sig->connect(cb);
    sig.reset();
    return connect;
}

int EventManager::removeEventListener(const char* estr)
{
    m_eventSignalMap.remove(estr);
}

int EventManager::removeEventCallback(const char* estr, bool _cb(EventBase &))
{
    boost::shared_ptr<boost::signals2::signal<bool (EventBase &)> > sig(m_eventSignalMap.find(estr));
    sig->disconnect(_cb);
    sig.reset();
    return 0;
}

EventManager* EventManager::getInstance()
{
    if (!p_instance)
        p_instance = new EventManager();
    return p_instance;
}

}

